local _G = _G;
local GetScreenWidth = _G.GetScreenWidth
local GetScreenHeight = _G.GetScreenHeight
local UIParent = _G.UIParent
local CreateFrame = _G.CreateFrame
local GetCursorPosition = _G.GetCursorPosition
local GameTooltip = _G.GameTooltip

local currentOffsetX, currentOffsetY =0, 0
local currentCursorAnchor = "BOTTOM";
local currentAnchorType = "CURSOR";
local currentOwner = UIParent;

local anchorOpposite = {
	BOTTOMLEFT = "TOPLEFT";
	BOTTOM = "TOP",
	BOTTOMRIGHT = "TOPRIGHT",
	LEFT = "RIGHT",
	RIGHT = "LEFT",
	TOPLEFT = "BOTTOMLEFT",
	TOP = "BOTTOM",
	TOPRIGHT = "BOTTOMRIGHT",
}

local function ReachorTooltip(anchorType, cursorAnchor, currentX, currentY)
	GameTooltip:ClearAllPoints();
	local scale = GameTooltip:GetScale();
	if anchorType == "PARENT" then
		GameTooltip:SetPoint(cursorAnchor, currentOwner, anchorOpposite[cursorAnchor], currentX, currentY)
	else --cursor
		local x, y = GetCursorPosition();
		x, y = x / scale + currentX, y / scale + currentY;
		GameTooltip:SetPoint(cursorAnchor, UIParent, "BOTTOMLEFT", x, y);
	end
end

--set cursor
function Icetip:SetDefaultAnchor(owner)
	local db = IcetipDB.Position;
	
	local anchor, offsetX, offsetY;
	currentOwner = owner;
	if owner == UIParent then
		anchor = db.unitAnchor;
		offsetX = db.unitOffsetX;
		offsetY = db.unitOffsetY;
	else
		anchor = db.frameAnchor;
		offsetX = db.frameOffsetX;
		offsetY = db.frameOffsetY;
	end

	if anchor:find("^CURSOR") or anchor:find("^PARENT") then
		if anchor == "CURSOR_TOP" and math.abs(offsetX) < 1 and math.abs(offsetY) < 0 then
			GameTooltip:SetOwner(owner, "ANCHOR_CURSOR");
		else
			currentOffsetX = offsetX;
			currentOffsetY = offsetY;
			currentCursorAnchor = anchor:sub(8);
			currsentAnchorType = anchor:sub(1, 6);
			GameTooltip:SetOwner(owner, "ANCHOR_CURSOR")--fix
			ReachorTooltip(currsentAnchorType, currentCursorAnchor, currentOffsetX, currentOffsetY)
		end
	--parent
	else
		GameTooltip:SetOwner(owner, "ANCHOR_NONE");
		GameTooltip:ClearAllPoints();
		GameTooltip:SetPoint(anchor, UIParnet, anchor, offsetX, offsetY)
	end
end
